package com.lhs.service;

import com.lhs.config.redis.ZiDeRedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class RateLimitService {

    @Autowired
    private ZiDeRedisUtil ziDeRedisUtil;

    /**
     * 基于Redis实现简单限流
     */
    public boolean allowRequest(String key, int maxAttempts, int timeWindow, TimeUnit timeUnit) {
        Long count = ziDeRedisUtil.increment(key, 1L);

        // 如果是第一次请求，设置过期时间
        if (count != null && count == 1) {
            ziDeRedisUtil.expire(key, timeWindow, timeUnit);
        }

        // 判断是否超过最大允许次数
        return count != null && count <= maxAttempts;
    }

    /**
     * 用户操作频率检查
     */
    public boolean checkUserOperationRate(Long userId, String operationType, String targetId, int maxAttempts, int timeWindow, TimeUnit timeUnit) {
        String key = String.format("rate:limit:%s:%s:%s:%s", operationType, userId, targetId, new SimpleDateFormat("yyyyMMddHH").format(new Date()));
        return allowRequest(key, maxAttempts, timeWindow, timeUnit);
    }
}